package Pet.Management.service;

import Pet.Management.domain.dto.NoticeDTO;
import Pet.Management.domain.entity.Notice;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.NoticeRepository;
import Pet.Management.repository.UserRepository;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class NoticeService {

    @Autowired
    private NoticeRepository noticeRepository;
    
    @Autowired
    private UserRepository userRepository;

    /**
     * 获取公告列表
     */
    public Page<NoticeDTO> getNoticeList(String title, String status, Pageable pageable) {
        Page<Notice> noticePage;
        
        if (title != null && !title.isEmpty() && status != null && !status.isEmpty()) {
            // 同时按标题和状态搜索
            noticePage = noticeRepository.findByTitleContainingAndStatus(title, status, pageable);
        } else if (title != null && !title.isEmpty()) {
            // 按标题搜索
            noticePage = noticeRepository.findByTitleContaining(title, pageable);
        } else if (status != null && !status.isEmpty()) {
            // 按状态搜索
            noticePage = noticeRepository.findByStatus(status, pageable);
        } else {
            // 获取所有公告
            noticePage = noticeRepository.findAll(pageable);
        }

        List<NoticeDTO> noticeDTOs = noticePage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        return new PageImpl<>(noticeDTOs, pageable, noticePage.getTotalElements());
    }

    /**
     * 获取公告详情
     */
    public NoticeDTO getNoticeById(Long id) {
        Notice notice = noticeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("公告不存在"));
        return convertToDTO(notice);
    }

    /**
     * 新增公告
     */
    @Transactional
    public NoticeDTO addNotice(NoticeDTO noticeDTO, Long userId) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeDTO, notice);
        
        // 设置发布者信息
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isPresent()) {
            notice.setPublisher(userOpt.get().getUsername());
        } else {
            notice.setPublisher("系统管理员");
        }
        
        // 如果是立即发布，则设置发布时间
        if ("1".equals(notice.getStatus())) {
            notice.setPublishTime(LocalDateTime.now());
        }
        
        Notice savedNotice = noticeRepository.save(notice);
        return convertToDTO(savedNotice);
    }

    /**
     * 修改公告
     */
    @Transactional
    public NoticeDTO updateNotice(NoticeDTO noticeDTO) {
        Notice notice = noticeRepository.findById(noticeDTO.getId())
                .orElseThrow(() -> new RuntimeException("公告不存在"));
        
        BeanUtils.copyProperties(noticeDTO, notice, "id", "createTime", "publisher");
        
        // 如果状态从草稿变为发布，则设置发布时间
        if ("1".equals(notice.getStatus()) && notice.getPublishTime() == null) {
            notice.setPublishTime(LocalDateTime.now());
        }
        
        Notice updatedNotice = noticeRepository.save(notice);
        return convertToDTO(updatedNotice);
    }

    /**
     * 删除公告
     */
    @Transactional
    public boolean deleteNotice(Long id) {
        if (noticeRepository.existsById(id)) {
            noticeRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    /**
     * 批量删除公告
     */
    @Transactional
    public boolean deleteNotices(List<Long> ids) {
        try {
            noticeRepository.deleteAllById(ids);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 发布公告
     */
    @Transactional
    public NoticeDTO publishNotice(Long id) {
        Notice notice = noticeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("公告不存在"));
        
        notice.setStatus("1");
        notice.setPublishTime(LocalDateTime.now());
        
        Notice publishedNotice = noticeRepository.save(notice);
        return convertToDTO(publishedNotice);
    }

    /**
     * 将实体转换为DTO
     */
    private NoticeDTO convertToDTO(Notice notice) {
        NoticeDTO dto = new NoticeDTO();
        BeanUtils.copyProperties(notice, dto);
        return dto;
    }
} 